<script setup>
import { ref, watch, watchEffect, nextTick } from 'vue';
import { useStore } from 'vuex';
import { computed } from 'vue';
import { useRouter, useRoute, onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router';
// 引入common里名为sort-button的组件
import SortButton from '../../../components/common/sort-button.vue';


const router = useRouter();
const route = useRoute();
const store = useStore();
const have = ref(false);
const discount = ref(false);

const currentPage = ref(1);


function init(to) {
  const params = {
    page: currentPage.value,
    pageSize: 10,
    categoryId: to.params.id,
  };
  store.dispatch('category/updateSubCategoryGoods', params);
}

// 初始化请求
init(route);
// 路由id变化时, 重新请求
onBeforeRouteUpdate(init);

const subCategoryGoodsList = computed(() => store.state.category.subCategoryGoodsList);

// // 记录;
let observer = null;
let lastObserver = null;

const hasNext = computed(() => subCategoryGoodsList.value.pages > currentPage.value);

watch(subCategoryGoodsList, async () => {
  // 如果请求的页面小于传过去的页面, 直接返回
  if (!hasNext.value) {
    return;
  }
  await nextTick();
  // 取消上一轮的观察
  if (observer) {
    observer.unobserve(lastObserver);
  }
  // 当clothes滚动到视野中时, dispatch
  observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting) {
        // 应该自己写的内容
        const params = {
          page: ++currentPage.value,
          pageSize: 10,
          categoryId: route.params.id,
        };
        store.dispatch('category/updateSubCategoryGoods', params);
      }
    },
    {
      root: null,
      rootMargin: '0px',
      threshold: 0.5,
    },
  );
  lastObserver = document.querySelector('.item:nth-last-child(5)');
  // 启动观察clothes.value是否进入视野
  observer.observe(lastObserver);
});

// 筛选条件列表
const subCategoryList = computed(() => store.state.category.subCategoryList);
// const subCategoryList = computed(() => store.getters['category/subCategoryFilters']);

// 重复请求以及报错
const stopWatchRoute = watchEffect(() => {
  route.params.id && store.dispatch('category/updateSubCategoryList', route.params.id);
});

onBeforeRouteLeave(() => {
  stopWatchRoute();
});

store.commit('category/RESET_SUB_CATEGORY_GOODS', {
  items: [],
  page: 1,
  pageSize: 10,
  counts: 0,
  pages: 1,
});
// 引入名为subCategoryFilters的getter
const subCategoryFilters = ref([]);
const subCategoryFiltersAttrs = ref([]);
watch(
  () => store.getters['category/subCategoryFilters'],
  () => {
    subCategoryFilters.value = store.getters['category/subCategoryFilters'].map((d)=>({
      ...d,
      properties: [
        {
          id: 'all',
          name: '全部',
        },
        ...d.properties,
      ],
    }));
    subCategoryFiltersAttrs.value = store.getters['category/subCategoryFilters'].map((d) => ({
      groupName: d.name,
      propertyName: '全部',
    }));
  });
async function onFilterChange() {
  await nextTick();
  const attrs = subCategoryFiltersAttrs.value.filter((d, i) => d.propertyName !== '全部' && i > 0);
  currentPage.value = 1;
  const params = {
    brandId: store.state.category.subCategoryList.brands.find((b) => b.name === subCategoryFiltersAttrs.value[0].propertyName)?.id || null,
    attrs,
    page: currentPage.value,
    pageSize: 10,
    categoryId: route.params.id,
  };
  store.dispatch('category/updateSubCategoryGoods', params);
}

// 进入商品详情页
function goPrudoct(id) {
  router.push({
    name: 'detail',
    params: {
      id,
    },
  });
}

// 价格排序
const sortValue = ref('');
</script>

<template>
  <div class="content-wrapper">
    <!--  -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/category/${subCategoryList.parentId}` }">
          {{ subCategoryList.parentName }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          {{ subCategoryList.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 筛选条件 -->
    <el-form class="sub-filter">
      <el-form-item
        v-for="(item, i) in subCategoryFilters"
        :key="item.id"
        :label="`${item.name}:`"
        class="sub-filter-item"
      >
        <el-radio-group
          v-model="subCategoryFiltersAttrs[i].propertyName"
          @change="onFilterChange"
        >
          <el-radio
            v-for="propertie in item.properties"
            :key="propertie.id"
            :label="propertie.name"
          />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <!-- 筛选物品图片 -->
    <div class="sub-show">
      <!-- 排序按钮框 -->
      <div class="sub-show-sorts">
        <!-- 按钮组 -->
        <div class="sorts">
          <div class="sort" @click="subFilter">默认排序</div>
          <div class="sort" @click="subFilter">最新商品</div>
          <div class="sort" @click="subFilter">最新人气</div>
          <div class="sort" @click="subFilter">评论最多</div>
          <SortButton
            v-model:value="sortValue"
          >
            价格排序
          </SortButton>
        </div>
        <!-- 有货无货 是否打折 -->
        <div class="have-discount">
          <el-checkbox v-model="have" label="仅显示有货商品" size="large" />
          <el-checkbox v-model="discount" label="仅显示特惠商品" size="large" />
        </div>
      </div>
      <!-- 物品图片框 -->
      <div class="sub-show-imgs">
        <MyCard
          class="item"
          v-for="gg in subCategoryGoodsList.items"
          :key="gg.id"
          :picture="gg.picture"
          :name="gg.name"
          :desc="gg.desc"
          :price="gg.price"
          @click="goPrudoct(gg.id)"
        />
      </div>
      <el-empty :image-size="200" description="亲 没有更多了">
      </el-empty>
    </div>
  </div>
</template>

<style scoped lang="scss">
.content-wrapper {
  width: 1240px;
  height: 100%;
  background-color: #f5f5f5;
  margin: 0 auto;

  // 面包屑
  .bread-crumbs {
    width: 100%;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    color: #666;
    margin-top: 20px;
  }

  // 筛选条件框
  .sub-filter {
    width: 100%;
    height: 100%;
    background-color: #fff;
    padding: 36px 20px;
    :deep(.el-form-item__label) {
      padding-right: 20px;
      justify-content: flex-start;
      width: 90px;
    }
    :deep(.el-radio__input) {
      display: none;
    }
    :deep(.el-radio__label) {
      max-width: 124px;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    :deep(.el-radio__input.is-checked+.el-radio__label) {
      color: $green;
    }
  }

  // 筛选物品图片
  .sub-show {
    width: 100%;
    height: 100%;
    padding: 16px 16px 0 32px;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    margin-top: 24px;

    // 排序按钮框
    .sub-show-sorts {
      width: 100%;
      height: 80px;
      display: flex;
      justify-content: space-between;

      // 按钮组
      .sorts {
        display: flex;
        align-items: center;
        .sort {
          flex: 1;
          margin-right: 24px;
          padding: 8px 24px;
          color: #999;
          outline: 1px solid #e4e4e4;
          border-radius: 2px;

          &:hover {
            background-color: $green;
            color: #fff;
            cursor: pointer;
          }
        }
      }

      // 有货无货 是否打折
      .have-discount {
        display: flex;
        align-items: center;
        .el-checkbox {
          margin-right: 24px;
        }
      }
    }

    // 物品图片框
    .sub-show-imgs {
      width: 100%;
      flex: 1;
      padding: 0 8px 16px;
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      // 间距
      grid-gap: 16px;
    }
  }

  :deep(.el-empty) {
    flex-direction: row;
  }
  :deep(.el-empty__image svg) {
    margin-left: -80px;
  }

}
</style>
